#!/usr/bin/env python
# -*- coding: utf-8 -*-

###
# Wifi + GPS fingerprint collection tool
# Copyright (c) 2008, Yura Zenevich, Jorge Silva, and Jamon Camisso
# Homepage http://wiki.scyp.atrc.utoronto.ca/wiki/WiFiPositioning
# Contact scyp@atrc.utoronto.ca
#    
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program, see enclosed file gpl-3.txt or browse to
# <http://www.gnu.org/licenses/gpl.txt>
###

import os
import re
import string
import time
#from math import fabs

def IwlistScan():
	#deviceName = os.popen("cat /proc/net/wireless |awk '{print $1}' |tail -n 1 |sed -e 's/://'").readlines()[0].strip('\n')
	deviceName = "wlan0"
	if deviceName == "face":
		return
	else:
		return os.popen("sudo /sbin/iwlist " + deviceName + " scan |grep -v 'IE:'").readlines()

def SingleScan():  
	print "Starting singlescan..."  
	macs = []
	signals = []
	aps = IwlistScan()
	addresses = "".join(aps)
	re_mac = re.compile("Address:.{18}")
	re_mac_strip = re.compile("(Address:.)|(:)")
	re_signal = re.compile("Signal level.-[0-9][0-9]")
	re_signal_strip = re.compile("Signal level.")
	for i in re_mac.findall(addresses):
		mac = re.sub(re_mac_strip, "", i)
		macs.append(mac)
	for i in re_signal.findall(addresses):
		signal = re.sub(re_signal_strip, "", i)
		signals.append(signal)
	return macs,signals

def MultiScan(quick,slow = 1):
	k = 1
	macs = []
	signals = []
	# Scan every 1.5s
	while k <= slow: 
		i = 1
		# Scan every 10ms
		while i <= quick:
			returnValue = SingleScan()
			j = 0
			while j < len(returnValue[0]):
				macs.append(returnValue[0][j])
				signals.append(returnValue[1][j])
				j += 1
			i += 1
			if i <= quick: # Don't wait if last
				time.sleep(0.01)
		k = k + 1
		if k <= slow: # Don't wait if last
			time.sleep(1.5)
		uniqueMacs, counts, averageSignals = AverageScan(macs, signals)
	return uniqueMacs, counts, RankScan(averageSignals)

def RankScan(signals):
	ranked = []
	# Rank with an inverse relationship in (0,1]
	for signal in signals:
		ranked.append(max(signals) / signal)
	return ranked

def AverageScan(macs,signals):
	uniqueMacs = []
	counts = []
	averageSignals = []
	for mac in macs:
		if uniqueMacs.count(mac) == 0:
			uniqueMacs.append(mac)
			counts.append(macs.count(mac))
			averageSignals.append(MacAverage(macs, signals, mac))
	return uniqueMacs, counts, averageSignals

def MacAverage(macs, signals, mac):
	total = 0.0
	i = 0
	while i < len(macs):
		if macs[i] == mac:
			total = total + float(signals[i])
		i = i + 1
	return total / float(macs.count(mac))
